package com.yj.springbootdynamic.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class DataSourceContextAop {


    @Pointcut("@annotation(com.yj.springbootdynamic.config.DataSourceSwitch)")
    public void pointCut(){

    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        boolean clear = false;
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            DataSourceSwitch annotation = method.getAnnotation(DataSourceSwitch.class);
            if (annotation!=null){

                String value = annotation.value();
                DataSourceRouter.context.set(value);
                log.info("设置数据源：{}",value);

            clear = annotation.clear();
            }
            return joinPoint.proceed();
        } finally {
            if (clear){
                DataSourceRouter.context.remove();
            }
        }
    }


}
